/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.usc.csci538.hw6.screens;

import edu.usc.csci538.hw6.data.CalendarEntry;
import java.util.Calendar;
import java.util.Date;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Spacer;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;

/**
 *
 * @author yaoli
 */
public class EventEditForm extends Form implements CommandListener {
    private final CalendarEntry event;
    private final OnRenderDisplayable parent;
    private final Command saveAction;
    private final Command cancelAction;
    private final MIDlet midlet;
    private final Runnable onSaveCallback;

    public EventEditForm(MIDlet midlet, CalendarEntry event, OnRenderDisplayable parent, Runnable onSave) {
        super("Edit Event");
        this.midlet = midlet;
        this.event = event;
        this.parent = parent;
        this.onSaveCallback = onSave;
        createForm();
        
        saveAction = new Command("Save", Command.OK, 1);
        cancelAction = new Command("Cancel", Command.CANCEL, 1);
        addCommand(saveAction);
        addCommand(cancelAction);
        setCommandListener(this);
    }
    
    public void commandAction(Command cmd, Displayable origin) {
        if (origin != this) {
            throw new RuntimeException();
        }
        final Alert infoAlert = new Alert("Saved!", "Changes saved", null, AlertType.INFO);
        infoAlert.setTimeout(800);
        if (cmd == saveAction) {
            saveForm();
        } else if (cmd == cancelAction) {
            Alert confirmAlert = new Alert("Save", "Save before exit or discard your changes?", null, AlertType.CONFIRMATION);
            final Command alertOkCommand = new Command("Save", Command.OK, 1);
            final Command alertCancelCommand = new Command("Discard", Command.CANCEL, 1);
            confirmAlert.setTimeout(Alert.FOREVER);
            confirmAlert.setCommandListener(new CommandListener() {
                public void commandAction(Command cmd, Displayable dis) {
                    Alert alt = infoAlert;
                    if (cmd == alertOkCommand) {
                        saveForm();
                    } else {
                        alt = new Alert("Discarded!", "Changes discarded", null, AlertType.INFO);
                    }
                    alt.setTimeout(800);
                    parent.onRender();
                    Display.getDisplay(midlet).setCurrent(alt, parent.getAsDisplayable());
                }
            });
            confirmAlert.addCommand(alertOkCommand);
            confirmAlert.addCommand(alertCancelCommand);
            Display.getDisplay(midlet).setCurrent(confirmAlert);
            return;
        } else {
            throw new RuntimeException();
        }
        parent.onRender();
        Display.getDisplay(midlet).setCurrent(infoAlert, parent.getAsDisplayable());
    }

    // Fields
    private final TextField subjectField = new TextField("Subject", "", 100, TextField.INITIAL_CAPS_SENTENCE);
    private final TextField locationField = new TextField("Location" , "", 100, TextField.INITIAL_CAPS_SENTENCE);
    private final DateField dateField = new DateField("Date", DateField.DATE);
    private final DateField startTimeField = new DateField("Starting Time", DateField.TIME);
    private final DateField endTimeField = new DateField("Ending Time", DateField.TIME);
    private final String REPEAT_CHOICES[] = {"Does not repeat", "Daily", "Weekly", "Monthly"};
    private final ChoiceGroup repeatField = new ChoiceGroup("Repeat?", Choice.POPUP, REPEAT_CHOICES, null);
    private final String ALARM_CHOICES[] = {"Off", "On"};
    private final ChoiceGroup alarmField = new ChoiceGroup("Alarm", Choice.POPUP, ALARM_CHOICES, null);
    private void createForm() {
        setTitle("Editing \"" + event.getSubject() + "\"");
        subjectField.setString(event.getSubject());
        locationField.setString(event.getLocation());
        
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(0));
        cal.set(Calendar.YEAR, event.getYear());
        cal.set(Calendar.MONTH, event.getMonth());
        cal.set(Calendar.DATE, event.getDate());
        dateField.setDate(cal.getTime());
        
        cal = Calendar.getInstance();
        cal.setTime(new Date(0));
        cal.set(Calendar.HOUR, event.getStartTimeHour());
        cal.set(Calendar.MINUTE, event.getStartTimeMinute());
        cal.set(Calendar.AM_PM, event.isStartTimeAM() ? Calendar.AM : Calendar.PM);
        startTimeField.setDate(cal.getTime());
        
        cal = Calendar.getInstance();
        cal.setTime(new Date(0));
        cal.set(Calendar.HOUR, event.getEndTimeHour());
        cal.set(Calendar.MINUTE, event.getEndTimeMinute());
        cal.set(Calendar.AM_PM, event.isEndTimeAM() ? Calendar.AM : Calendar.PM);
        endTimeField.setDate(cal.getTime());
        
        int repeatIndex = 0;
        switch (event.getRepeat()) {
            case CalendarEntry.REPEAT_NONE:
                repeatIndex = 0; break;
            case CalendarEntry.REPEAT_DAILY:
                repeatIndex = 1; break;
            case CalendarEntry.REPEAT_WEEKLY:
                repeatIndex = 2; break;
            case CalendarEntry.REPEAT_MONTHLY:
                repeatIndex = 3; break;
            default:
                throw new RuntimeException();
        }
        repeatField.setSelectedIndex(repeatIndex, true);
        
        int alarmIndex = 0;
        if (event.alarmEnabled()) {
            alarmIndex = 1;
        }
        alarmField.setSelectedIndex(alarmIndex, true);
        
        append(subjectField);
        append(locationField);
        append(new Spacer(0, 2));
        append(dateField);
        append(repeatField);
        append(new Spacer(0, 2));
        append(alarmField);
        append(startTimeField);
        append(endTimeField);
    }

    private void saveForm() {
        event.setSubject(subjectField.getString().trim());
        event.setLocation(locationField.getString().trim());
        
        int year, month, date, hour, min;
        boolean isAM;
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateField.getDate());
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH);
        date = cal.get(Calendar.DATE);
        event.setDate(year, month, date);
        
        cal.setTime(startTimeField.getDate());
        hour = cal.get(Calendar.HOUR);
        min = cal.get(Calendar.MINUTE);
        isAM = cal.get(Calendar.AM_PM) == Calendar.AM;
        event.setStartTime(hour, min, isAM);
        
        cal.setTime(endTimeField.getDate());
        hour = cal.get(Calendar.HOUR);
        min = cal.get(Calendar.MINUTE);
        isAM = cal.get(Calendar.AM_PM) == Calendar.AM;
        event.setEndTime(hour, min, isAM);
        
        int repeatVal;
        switch (repeatField.getSelectedIndex()) {
            case 0:
                repeatVal = CalendarEntry.REPEAT_NONE; break;
            case 1:
                repeatVal = CalendarEntry.REPEAT_DAILY; break;
            case 2:
                repeatVal = CalendarEntry.REPEAT_WEEKLY; break;
            case 3:
                repeatVal = CalendarEntry.REPEAT_MONTHLY; break;
            default:
                throw new RuntimeException();
        }
        event.setRepeat(repeatVal);
        
        if (alarmField.getSelectedIndex() == 0) {
            event.setAlarmEnabled(false);
        } else {
            event.setAlarmEnabled(true);
        }
        if (onSaveCallback != null) {
            onSaveCallback.run();
        }
    }

}
